<?php
$is_command = php_sapi_name() != 'cli' ? false : true;

if (!$is_command) {
    exit('不是命令行');
}

date_default_timezone_set('PRC');

ini_set('display_errors', 0);
ini_set('log_errors', 1);
set_time_limit(0);
ini_set('memory_limit','512M');
error_reporting(E_ALL & ~E_NOTICE);

define('DS', DIRECTORY_SEPARATOR);

//自动加载

require("config.php");
//require("xlsxwriter.class.php");
require(FRAMEROOT . "/lib/xlsxwriter.class.php");

// s 开妈时间 e 结束时间 t 表名
//$parms = getopt("s:e:t:");

$table = 't_areaex';
$sheetObj = null;   //导出Excel文件对象

$pdo = new \PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME, DB_USER, DB_PASSWORD);

$pdo->setAttribute(\PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false);

$pageSize = 20000; //每个文件多少条记录
$total = getTotal();    //总符合记录数

$where = [];
$loopNum = ceil($total/$pageSize);

$savePath = getSavePath();  //保存路径
$tarPath = dirname($savePath);  //打包路径

//导出
$timeStart = microtime(true);

//sheetInit();  //初始化phpexcel
export($loopNum, $pageSize, $savePath);

zipFile($tarPath, $savePath);

//上传文件
saveTotfs();

//修改可下载状态
updDownloadStatus();
echo floor((memory_get_peak_usage())/1024/1024)."MB";
echo "\n";
echo microtime(true) - $timeStart;
echo "\n";
exit;


/**
 * 记录总数
 * @param  integer $where [description]
 * @return [type]         [description]
 */
function getTotal($where = 1)
{
    global $table;
    $db = new MySql_();
    $total = $db->count($table, $where);
    return $total;
}

/**
 * 执行导出
 * @param  [int] $loopNum  [循环次数]
 * @param  [int] $pageSize [每页记录数]
 * @param  [int] $savePath [保存路径]
 * @param  array  $where    [查询条件]
 * @return [bool]           [bool]
 */
function export($loopNum, $pageSize, $savePath, $where = [])
{
    $cache = new cache();

    $i = 0;
    $pids = array();

    while ($i < $loopNum) {
        // $db = new MySql_();

        $list = getData($i+1, $pageSize, $where);

        if (empty($list)) {
            break;
        }

        //写入缓存
        //$key = 'excel_'.$i.'_'.$pageSize;
        //$res = $cache->add($key, $list);

        //保存excel
        //saveToFile($list, $i, $pageSize);

        //保存csv
        saveToCsv($list, $i, $pageSize);

        //启动进程写入文件
        //$pid = pcntl_fork();
        //if ($pid == -1) {
        //    die('error');
        //}elseif(0 == $pid){
        //    saveToFile($cache, $key, $i, $pageSize);
        //    exit(1);
        //}else{
        //    $pids[$pid] = $i;
        //}

        $i++;
        sleep(1);
    }

    //while (count($pids) > 0) {
    //    foreach ($pids as $p => $num) {
    //        $res = pcntl_waitpid($p, $status, WNOHANG);

    //        if ($res == -1 || $res > 0) {
    //            $code = pcntl_wexitstatus($status);
    //            if ($code == 1) {
    //                // echo '正常';
    //            } else {
    //                // echo '失败';
    //            }

    //            unset($pids[$p]);
    //        }
    //    }

    //    sleep(1);
    //}

    return true;
}

/**
 * [sheetInit 初始化EXCEL导出类]
 * @return [type] [description]
 */
function sheetInit()
{
    $columns = array(
        '编号',
        '昵称',
        '会员ID',
        '积分',
        '余额',
        '帐号',
        '业务',
        '订单',
        '备注',
        '操作者',
        '创建时间'
    );

    $sheetHeader = array_fill_keys($columns, 'string');

    global $sheetObj;
    $sheetObj = new XLSXWriter();
    $sheetObj->writeSheetHeader('Sheet1',  $sheetHeader);
}

/**
 * [saveToFile 保存为EXCEL文件]
 * @param  [type] $list     [数据源]
 * @param  [type] $i        [当前页]
 * @param  [type] $pageSize [每页面记录数]
 * @return [type]           [description]
 */
function saveToFile($list, $i, $pageSize)
{
    if (empty($list)) {
        return true;
    }

    global $sheetObj;
    if (!empty($sheetObj)) {
        $writer = clone $sheetObj;
    }else{
        $writer = new XLSXWriter();
    }

    //$writer->writeSheetHeader('Sheet1',  $sheetHeader);

    foreach ($list as $k => $v) {
        $rowData = array(
            $v['ae_code'],
            $v['ae_code'],
            $v['ae_code'],
            $v['ae_code'],
            $v['ae_code'],
            $v['ae_code'],
            $v['ae_code'],
            $v['ae_code'],
            $v['ae_code'],
            $v['ae_code'],
            $v['ae_code'],
        );

        $writer->writeSheetRow('Sheet1', $rowData );
    }

    unset($list, $rowData);

    $startNum = ($i*$pageSize) + 1;
    $endNum = $startNum + $pageSize - 1;
    $fileName =  date('YmdH').'_' . $startNum. '_' . $endNum.'.xlsx';

    global $savePath;
    //$fullPath = $savePath.DS.$fileName;

    //if (file_exists($fullPath)) {
    //    @unlink($fullPath);
    //}

    //$fp = fopen($fullPath);

    //fwrite($fp, $writer->writeToString());
    //fclose();
    $writer->writeToFile($savePath . DS .$fileName);
    return true;
}

function getSavePath()
{
    //$dir = ROOT_PATH .'uploads';
    $dir = dirname(__FILE__).DS.'upload';
    $savePath = $dir.DS.date('Ymd');

    if (!is_dir($savePath)) {
        if (false == mkdir($savePath, "755", true)){
            exit(-1);
        }
    }

    return $savePath;
}

/**
 * 获取数据
 * @param  [type] $db       [description]
 * @param  [type] $i        [description]
 * @param  [type] $pageSize [description]
 * @param  array  $where    [description]
 * @return [type]           [description]
 */
function getData($i, $pageSize, array $where = [])
{
    global $pdo;
    global $table;

    //例如生成器
    $sql =  "SELECT * FROM $table limit " . ($i-1) * $pageSize .','. $pageSize;
    $list = $pdo->query($sql);

    return $list;
}

/**
 * 创建目录
 * @param  [type] $filename [description]
 * @return [type]           [description]
 */
function makedir($filename){
    return (mkdir($filename, 0755));
}

/**
 * [保存到cvs文件]
 * @param  [type] &$list    [数据源]
 * @param  [type] $i        [description]
 * @param  [type] $pageSize [description]
 * @return [type]           [description]
 */
function saveToCsv(&$list, $i, $pageSize)
{
    global $savePath;
    $seperator = '^';
    //$enclosure = "";
    $startNum = ($i*$pageSize) + 1;
    $endNum = $startNum + $pageSize - 1;
    $fileName =  date('YmdH').'_' . $startNum. '_' . $endNum.'.xls';

    if (file_exists($fileName)) {
        @unlink($savePath.DS.$fileName);
    }

    $fp = fopen($savePath.DS.$fileName, 'a');

    $columns = array(
        '编号',
        '昵称',
        '会员ID',
        '积分',
        '余额',
        '帐号',
        '业务',
        '订单',
        '备注',
        '操作者',
        '创建时间'
    );

    mb_convert_variables('GBK', 'UTF-8', $columns);

    fputcsv($fp, $columns, $seperator);

    foreach ($list as $k => $v) {
        $rowData = array(
            ' '.$v['ae_code'],
            ' '.$v['ae_code'],
            ' '.$v['ae_code'],
            ' '.$v['ae_code'],
            ' '.$v['ae_code'],
            ' '.$v['ae_code'],
            ' '.$v['ae_code'],
            ' '.$v['ae_code'],
            ' '.$v['ae_code'],
            ' '.$v['ae_code'],
            ' '.$v['ae_code'],
        );

        //array_walk($rowData, function(&$v){
        //    return ' '.$v;
        //});

        //print_r($rowData);exit;

        mb_convert_variables('GBK', 'UTF-8', $rowData);

        fputcsv($fp, $rowData, $seperator);
    }

    unset($list, $v);
    fclose($fp);
}

//用命令行打包
function zipFile($tarPath, $savePath)
{
    if (!is_dir($savePath) && !is_dir($tarPath)) {
        echo '打包路径不正确';
    }else{
        $path = explode(DS, $savePath);
        $finialPath = array_pop($path);
        $command = 'cd '.$tarPath.' && tar -cf ./'.date('Ymd').'.tar.gz '. $finialPath. ' 2>&1';
        exec($command);
    }
}
?>
